﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using FileSystem.Models;
using FileSystem.Services.IServices;
using SQLite;

namespace FileSystem.Services.Realization {
    /// <summary>
    /// 根目录项存储
    /// </summary>
    public class RootDirItemStorage : IRootDirItemStorage {
        // ******** 公开变量
        /// <summary>
        /// RootDirItemTable文件路径
        /// </summary>
        public static readonly string DbPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);

        /// <summary>
        /// RootDirItemTable数据库连接
        /// </summary>
        private SQLiteAsyncConnection _connection;

        public SQLiteAsyncConnection Connection =>
            _connection ?? (_connection = new SQLiteAsyncConnection(DbPath));

        // ******** 私有变量
        /// <summary>
        /// TableDb文件名
        /// </summary>
        private const string DbName = "RootDirItemTable.sqlite3";

        /// <summary>
        /// 偏好存储服务
        /// </summary>
        private IPreferenceStorage _preferenceStorage;

        // ******** 继承方法

        /// <summary>
        /// 初始化根目录存储
        /// </summary>
        public async Task InitializeAsync() {
            // RootDirItemTable.sqlite3 文件初始化
            await Connection.CreateTableAsync<RootDirItem>();

            //将程序自带的用户写入表中,不用AddAsync,减少耦合度
            foreach (var user in UserConst.Users)
                await Connection.InsertAsync(new RootDirItem {
                    UserName = user.UserName, DirItemName = user.UserName + ":"
                });
            
            _preferenceStorage.Set(RootDirItemStorageConstants.VersionKey,
                RootDirItemStorageConstants.Version);
        }

        /// <summary>
        /// 根目录项存储是否已经初始化
        /// </summary>
        public bool IsInitialized() {
            return _preferenceStorage.Get(
                    RootDirItemStorageConstants.VersionKey,
                    RootDirItemStorageConstants.DefaultVersion) ==
                RootDirItemStorageConstants.Version;
        }

        /// <summary>
        /// 增加根目录项
        /// </summary>
        /// <param name="rootDirItem">要添加的根目录项</param>
        public async Task AddAsync(RootDirItem rootDirItem) {
            await Connection.InsertAsync(rootDirItem);
        }

        /// <summary>
        /// 删除根目录项
        /// </summary>
        /// <param name="rootDirItem">要删除的根目录项</param>
        public async Task RemoveAsync(RootDirItem rootDirItem) {
            await Connection.DeleteAsync(rootDirItem);
        }

        /// <summary>
        /// 修改根目录项的属性
        /// </summary>
        /// <param name="rootDirItem">被修改的根目录项</param>
        /// <param name="property">要修改的属性</param>
        /// <param name="newContent">新值</param>
        public async Task ModifyProperty(RootDirItem rootDirItem,
            RootDirItemConst.Property property, string newContent) {
            switch (property) {
                case RootDirItemConst.Property.UserName: {
                    rootDirItem.UserName = newContent;
                    await Connection.InsertOrReplaceAsync(rootDirItem);
                    break;
                }
                case RootDirItemConst.Property.DirItemName: {
                    rootDirItem.DirItemName = newContent;
                    await Connection.InsertOrReplaceAsync(rootDirItem);
                    break;
                }
            }
        }

        /// <summary>
        /// 根据用户名获得一个根目录项
        /// </summary>
        /// <param name="userName">用户名</param>
        public async Task<RootDirItem> GetRootDirItemAsync(string userName) {
            return await Connection.Table<RootDirItem>()
                .FirstOrDefaultAsync(p => p.UserName == userName);
        }

        /// <summary>
        /// 获得所有的根目录项
        /// </summary>
        public async Task<IList<RootDirItem>> GetRootDirItemsAsync() {
            return await Connection.Table<RootDirItem>().ToListAsync();
        }

        /// <summary>
        /// 判断根目录项是否存在
        /// </summary>
        /// <param name="userName">用户名</param>
        public async Task<bool> Exist(string userName) {
            var item = await Connection.Table<RootDirItem>()
                .FirstOrDefaultAsync(p => p.UserName == userName);
            if (item == null)
                return false;
            else
                return true;
        }


        // ******** 公开方法
        /// <summary>
        /// 根目录项存储
        /// </summary>
        public RootDirItemStorage(IPreferenceStorage preferenceStorage) {
            _preferenceStorage = preferenceStorage;
        }

        /// <summary>
        /// 关闭数据库
        /// </summary>
        public async Task CloseAsync() {
            await Connection.CloseAsync();
        }

        // ******** 私有方法
    }
}